import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import NProgress from 'nprogress'
import viewPageComponent from '@/pages/App'


//home
import homeComponent from '@/pages/home'
import homeComponent3 from '@/pages/home3'
import homeComponent2 from '@/pages/home2'
import homeComponent4 from '@/pages/home4'
//login
import loginComponent from '@/pages/user/login'

Vue.use(Router)

let routes = [

    {
        path: '/user/login',
        name: 'login',
        component: loginComponent
    },
    {
        path: '/',
        redirect: '/home1',
        component: viewPageComponent,
        children: [{
            path: '/home1',
            name: 'home',
            component: homeComponent,
            meta: {
                title: "主页",
                auth: true
            }
        },
            {
                path: '/home2',
                name: 'home2',
                component: homeComponent2,
                meta: {
                    title: "主页",
                    auth: true
                }
            },
            {
                path: '/home3',
                name: 'home3',
                component: homeComponent3,
                meta: {
                    title: "主页",
                    auth: true
                }
            },
            {
                path: '/home4',
                name: 'home4',
                component: homeComponent4,
                meta: {
                    title: "主页",
                    auth: true
                }
            }
        ]
    }
]


const router = new Router({
    routes,
    mode: 'hash', //default: hash ,history
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return {x: 0, y: 0}
        }
    }
})
//全局路由配置
//路由开始之前的操作
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

router.beforeEach((to, from, next) => {
    NProgress.done().start()
    if (to.path == '/user/login') {
        delCookie('name')
    }
    let user = getCookie('name')
    if (!user && to.path != '/user/login') {
        next({path: '/user/login'})
    } else {
        next()
    }
})
//路由完成之后的操作
router.afterEach(route => {
    NProgress.done()
})

export default router
